package com.eshipenet.shipnet.shiprpc.service;

import com.eshipenet.shipnet.ship.FindAllResult;
import com.eshipenet.shipnet.ship.Page;
import com.eshipenet.shipnet.ship.Query;
import com.eshipenet.shipnet.ship.ShipGovernor;
import com.eshipenet.shipnet.ship.grpc.ShipGovernorEdge;
import com.eshipenet.shipnet.shiprpc.util.BuilderUtil;
import com.eshipenet.shipnet.shiprpc.util.FormatSql;
import com.eshipenet.shipnet.shiprpc.util.PageUtil;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.query.FieldsQueryCursor;
import org.apache.ignite.cache.query.QueryCursor;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.cache.query.SqlQuery;
import org.apache.ignite.services.ServiceContext;
import org.json4s.JsonAST;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import scala.Option;
import squirrel.JSONQuery;

import javax.cache.Cache;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class ShipGovernorServiceImp implements ShipGovernorService {
  private Logger logger = LoggerFactory.getLogger("ShipGovernorServiceImp");
  private IgniteCache<String, ShipGovernor> cache ;

  public ShipGovernorServiceImp(IgniteCache<String, ShipGovernor> cache) {
    this.cache = cache;
  }

  @Override
  public FindAllResult findAll(JSONQuery jsonQuery,int limit,int offset) {
    Query query = FormatSql.getFormatSql(jsonQuery);
    SqlQuery<String, ShipGovernor> sql = new SqlQuery<>(com.eshipenet.shipnet.ship.ShipGovernor.class, query.getSql());
    sql.setArgs(FormatSql.sqlValueToObject(query.getWhere()));
    logger.info("query ShipGovernor list sql  {}",sql);
    QueryCursor<Cache.Entry<String, ShipGovernor>> cursor = cache.query(sql);
    Iterator<Cache.Entry<String, ShipGovernor>> iterator = cursor.iterator();

    List<ShipGovernorEdge> list = new ArrayList<>();
    //查询数量
    JSONQuery countJsonQuery = JSONQuery.apply(jsonQuery.from(),
            jsonQuery.where(),
            Option.apply(new JsonAST.JString("count(*) as count")),
            jsonQuery.includes(),
            jsonQuery.offset(),
            jsonQuery.limit());

    Query countQuery = FormatSql.getFormatSql(countJsonQuery);
    SqlFieldsQuery sqlFieldsQuery = new SqlFieldsQuery(countQuery.getSql());
    sqlFieldsQuery.setArgs(FormatSql.sqlValueToObject(countQuery.getWhere()));
    logger.info("query ShipGovernor count sql  {}",sqlFieldsQuery);
    int totalCount = 0;
    try (FieldsQueryCursor<List<?>> cursor1 = cache.query(sqlFieldsQuery)) {
      for (List<?> row : cursor1) {
        totalCount = Integer.parseInt(row.get(0).toString());
      }

    }

    if(totalCount<1){
      return  new FindAllResult<>(list,totalCount,null,null,false,false);

    }

    //分页工具
    Page page = PageUtil.page(limit, totalCount, offset);
    //起点数据
    int start = page.getStartIndex();
    //结点数据
    int end = page.getEndIndex();
    //计数器
    int times = 0;

    while (iterator.hasNext()) {
      Cache.Entry<String, com.eshipenet.shipnet.ship.ShipGovernor> p = iterator.next();
      if (p != null) {

        if (list.size() < limit) {
          if (times >= start && times < end) {
            ShipGovernorEdge shipGovernorEdge = BuilderUtil.shipGovernorEdgeBuilder(p);
            list.add(shipGovernorEdge);
          }
        } else {
          break;
        }
      }
      times++;
    }

    return  new FindAllResult<>(list,
            totalCount,
            list.get(0).getCursor(),
            list.get(list.size()-1).getCursor(),
            page.isHasNextPage(),
            page.isHasPreviousPage());
  }


  @Override
  public ShipGovernor createOne(ShipGovernor shipGovernor) {

    cache.put(shipGovernor.getId(),shipGovernor);

    shipGovernor = cache.get(shipGovernor.getId());

    return shipGovernor;
  }

  @Override
  public ShipGovernor updateOne(String id, ShipGovernor shipGovernor) {
    ShipGovernor old = cache.get(id);

    shipGovernor = new ShipGovernor(
            shipGovernor.getName(),
            shipGovernor.getDescription(),
            shipGovernor.getAvatar(),
            shipGovernor.getInfo(),
            old.getCreatedAt(),
            shipGovernor.getUpdatedAt(),
            id
    );


    cache.put(id, shipGovernor);

    return shipGovernor;
  }

  @Override
  public ShipGovernor deleteOne(String id) {

    ShipGovernor old = cache.get(id);
    ShipGovernor shipGovernor = new ShipGovernor(
            old.getName(),
            old.getDescription(),
            old.getAvatar(),
            old.getInfo(),
            old.getCreatedAt(),
            old.getUpdatedAt(),
            id);

    SqlFieldsQuery query = new SqlFieldsQuery("delete from  ShipGovernor  where id=? ");
    cache.query(query.setArgs(id)).getAll();
    logger.info("delete ShipGovernor by id  sql  {}",query);
    return shipGovernor;
  }

  @Override
  public int getShipGovernorCountById(String id) {
    //查询数据总数
    SqlFieldsQuery query = new SqlFieldsQuery("select count(id) from  ShipGovernor where id=? ");

    query.setArgs(id);
    logger.info("query ShipGovernor count by id  sql  {}",query);
    //数据总数
    java.util.List<?> getCount = cache.query(query).getAll().get(0);

    Object obj = getCount.get(0);

    int count = Integer.parseInt(obj.toString());

    return count;
  }


  @Override
  public void cancel(ServiceContext ctx) {}

  @Override
  public void init(ServiceContext ctx) throws Exception {}

  @Override
  public void execute(ServiceContext ctx) throws Exception {}


}
